<template>
	<div>
		<slot name="left"></slot>
		<span ref="number" :class="countClass" :id="eleId"></span>
		<slot name="right"></slot>
	</div>
</template>

<script>
	import CountUp from 'countup';
	// 设置样式(方式1：引入less文件)
	// import './count-to.less';

	export default {
		name: "Count-to",
		computed: {
			eleId() {
				return `count_up_${this._uid}`;
			},
			countClass() {
				return [`count_to_number`, this.className]
			}
		},
		data() {
			return {
				counter: {}
			}
		},
		/**给组件传入样式*/
		props: {
			/**
			 * 起始值
			 */
			startVal: {
				type: Number,
				default: 0
			},
			/**
			 * 最终值
			 */
			endVal: {
				type: Number,
				required: true // 必填
			},
			/**
			 * 小数点后保留几位小数
			 */
			decimals: {
				type: Number,
				default: 0
			},
			/**
			 * 动画延迟
			 */
			delay: {
				type: Number,
				default: 0
			},
			/**
			 * 渐变时长
			 */
			duration: {
				type: Number,
				default: 1
			},
			/**
			 * 是否使用变速效果
			 */
			useEasing: {
				type: Boolean,
				default: false
			},
			/**
			 * 是否设置分组
			 */
			useGrouping: {
				type: Boolean,
				default: true
			},
			/**
			 * @description 分组符号
			 */
			separator: {
				type: String,
				default: ','
			},
			/**
			 * 整数和小数分隔符号
			 */
			decimal: {
				type: String,
				default: '.'
			},
			/**
			 * 类名
			 */
			className: {
				type: String,
				default: ''
			}
		},
		methods: {
			/**
			 * 获取<span/>标签的数值
			 */
			getCount() {
				// 获取当前的DOM
				// console.log(this.$refs.number);
				return this.$refs.number.innerText;
			},
			emitEndEvent() {
				setTimeout(() => {
					this.$emit('on-animation-end', Number(this.getCount()));
				}, this.duration * 1000 + 5);
			}
		},
		watch: {
			endVal(newVal, oldVal) {
				this.counter.update(newVal);
				this.emitEndEvent();
			}
		},
		mounted() {
			this.$nextTick(() => {
				this.counter = new CountUp(this.eleId, this.startVal, this.endVal, this.decimals, {
					useEasing: this.useEasing,
					useGrouping: this.useGrouping,
					separator: this.separator,
					decimal: this.decimal
				});
				setTimeout(() => {
					this.counter.start();
					this.emitEndEvent();
				}, this.delay)
			})
		}
	}
</script>

<style lang="less" scoped>
	/*设置样式(方式2)*/
	/*.count_to_number {
		color: palevioletred;
	}*/

	/*设置样式(方式3)*/
	@import "count-to";
</style>
